package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.adapter.KeepServerAdapter;
import com.longqinuo.mycarservice.entity.KeepServer;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.utils.SpaceItemDecoration;
import com.longqinuo.mycarservice.view.LruImageCache;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link KeepServerFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class KeepServerFragment extends Fragment implements View.OnClickListener {
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mEdit;

    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private int lastVisibleItem;  //最后一个可见Item的索引值

    private KeepServerAdapter mAdapter;
    private List<KeepServer> mList;
    private LinearLayoutManager layoutManager;
    private FragmentManager manager;
    private FragmentTransaction mTransaction;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private static RequestQueue queue;
    private static ImageLoader imageLoader;
    private Map<String, String> map = new HashMap<>();   //post请求参数集合

    private OnFragmentInteractionListener mListener;
    private ImageView iv_up_price_server;
    private ImageView iv_down_price_server;
    private LinearLayout ll_price_order_server;
    private ImageView iv_up_count_server;
    private ImageView iv_down_count_server;
    private LinearLayout ll_count_order_server;
    private boolean isPriceUp = true;  //价格升序
    private boolean isCountUp = false;  //数量升序

    public KeepServerFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment KeepServerFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static KeepServerFragment newInstance(String param1, String param2) {
        KeepServerFragment fragment = new KeepServerFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        init();
    }

    private void init() {
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue, lruImageCache);

        manager = getActivity().getSupportFragmentManager();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_keep_server, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        manager = getActivity().getSupportFragmentManager();
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_keep_server_list);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_keep_server);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent);
        swipeRefreshLayout.setProgressViewOffset(false, 0,
                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));

        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mEdit = (ImageView) view.findViewById(R.id.iv_top_option);

        mBack.setOnClickListener(this);
        mTitle.setText("维保套餐");
        mEdit.setVisibility(View.INVISIBLE);

        iv_up_price_server = (ImageView) view.findViewById(R.id.iv_up_price_server);
        iv_down_price_server = (ImageView) view.findViewById(R.id.iv_down_price_server);
        ll_price_order_server = (LinearLayout) view.findViewById(R.id.ll_price_order_server);
        ll_price_order_server.setOnClickListener(this);
        iv_up_count_server = (ImageView) view.findViewById(R.id.iv_up_count_server);
        iv_down_count_server = (ImageView) view.findViewById(R.id.iv_down_count_server);
        ll_count_order_server = (LinearLayout) view.findViewById(R.id.ll_count_order_server);
        ll_count_order_server.setOnClickListener(this);
        initData();

    }

    private void initData() {
        mList = new ArrayList<>();

        mAdapter = new KeepServerAdapter(mList, R.layout.keep_server_list_item, imageLoader);
        layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        int space = getResources().getDimensionPixelSize(R.dimen.recycler_divede_line);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(space));
        mAdapter.setOnItemClickListener(new KeepServerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                mTransaction = manager.beginTransaction();
                mTransaction.replace(R.id.ll_main_layout, MealInfoFragment.newInstance(mList.get(position).getId() + "", ""), "MeaLInfo");
                mTransaction.addToBackStack("MeaLInfo");
                mTransaction.commit();
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        map.put("order",1+"");  //价格升序
        iv_up_price_server.setSelected(isPriceUp);
        iv_down_count_server.setSelected(!isCountUp);

        new getData().execute();      //请求网络 查找车辆
        setListener();  //设置下拉刷新监听器
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                0：当前屏幕停止滚动；1时：屏幕在滚动 且 用户仍在触碰或手指还在屏幕上；2时：随用户的操作，屏幕上产生的惯性滑动；
                //               滑动状态停止并且剩余两个item时自动加载
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 2 >= layoutManager.getItemCount()) {  //触发上啦加载
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //                获取加载的最后一个可见视图在适配器的位置。
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();

            }

        });
    }

    private void setListener() {  //设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new getData().execute();
            }

        });
    }

    private class getData extends AsyncTask<Void, Void, Void> {  //异步任务 请求网络

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            swipeRefreshLayout.setRefreshing(true);
        }

        @Override
        protected Void doInBackground(Void... params) {
            mList.clear();
            requestCar();  //查询车辆
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    private void requestCar() {  //请求查找套餐

        StringRequest request = new StringRequest(Request.Method.POST, PathUtils.KEEP_SERVER, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Gson gson = new Gson();
                String jsonData = null;
                try {

                    JSONObject jsonObject = new JSONObject(s);
                    int code = jsonObject.getInt("code");
                    if (code == 0) {
                        jsonData = jsonObject.getString("data");
                        List<KeepServer> carList = gson.fromJson(jsonData, new TypeToken<List<KeepServer>>() {
                        }.getType());
                        mList.addAll(carList);
                        mAdapter.notifyDataSetChanged();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(">>>>>", "套餐" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                return map;
            }
        };
        queue.add(request);

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_top_back:
                manager.popBackStack();
                break;
            case R.id.ll_price_order_server:  //按价格排序
                isPriceUp = !isPriceUp;
                map.remove("order");
                if (isPriceUp) {   //升序

                    map.put("order",1+"");
                } else {
                    map.put("order",2+"");
                }
                iv_up_price_server.setSelected(isPriceUp);
                iv_down_price_server.setSelected(!isPriceUp);
                new getData().execute();
                break;
            case R.id.ll_count_order_server:  //按预约数量排序
                isCountUp = !isCountUp;
                map.remove("order");
                if (isCountUp) {   //升序

                    map.put("order",3+"");
                } else {
                    map.put("order",4+"");
                }
                iv_up_count_server.setSelected(isCountUp);
                iv_down_count_server.setSelected(!isCountUp);
                new getData().execute();
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
